package com.caiwangdai.app.utils

import android.content.Context
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.support.v4.content.FileProvider
import android.text.TextUtils
import com.caiwangdai.app.BuildConfig
import java.io.File
import java.text.SimpleDateFormat
import java.util.*


object FileUtils {

    val MEDIA_TYPE_IMAGE = 0
    val MEDIA_TYPE_VIDEO = 1


    fun getIDCardOutputFile(mType: Int): File? {
        val rootDir = Environment.getExternalStorageDirectory()
        val mMediaFileDir = File(rootDir.toString() + "/" + BuildConfig.APPNAME)
        if (!mMediaFileDir.exists()) {
            if (!mMediaFileDir.mkdir()) {
                return null
            }
        }
        var mMediaFile: File? = null
        /**  创建文件名    */
        val mFileName = SimpleDateFormat("yyyyMMddHHmmss").format(Date())
        when (mType) {
            MEDIA_TYPE_IMAGE -> mMediaFile = File(mMediaFileDir.path + File.separator + "IMG_" + mFileName + ".jpg")
            MEDIA_TYPE_VIDEO -> mMediaFile = File(mMediaFileDir.path + File.separator + "VID_" + mFileName + ".mp4")
            else -> mMediaFile = null
        }
        return mMediaFile
    }

    //是否存在文件
    fun isFileExist(filePath: String): Boolean {
        if (TextUtils.isEmpty(filePath)) {
            return false
        }

        val file = File(filePath)
        return file.exists() && file.isFile
    }

    private val FilePreoviderAuthorities = "${BuildConfig.APPLICATION_ID}.fileprovider"//类名+fileprovider

    /**
     * 获取文件的Uri
     * 兼容7.0
     */
    fun getUriForFile(context: Context?, file: File?): Uri {
        if (context == null || file == null) {
            throw NullPointerException()
        }
        val uri: Uri
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(context.applicationContext, FilePreoviderAuthorities, file)
        } else {
            uri = Uri.fromFile(file)
        }
        return uri
    }


}